package com.daybook.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.daybook.pojo.User;


/**
 * Servlet Filter implementation class File1_UserFilter
 */
@WebFilter(filterName="/File1_UserFilter", urlPatterns={"/public_user/*"})
public class File1_UserFilter implements Filter {

    /**
     * Default constructor. 
     */
    public File1_UserFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpSession session =  ((HttpServletRequest)request).getSession();
		
		User user = (User)session.getAttribute("user");
		String reqPath = ((HttpServletRequest)request).getRequestURI();
		String[] urls  = reqPath.split("/");
		String target = urls[3];
		
		if((user == null) && 
				!(target.equals("login.jsp")) && 
				!(target.equals("register.jsp")) && 
				!(target.equals("index.jsp")) && 
				!(target.equals("shop.jsp")) && 
				!(target.equals("style.css")) && 
				!(target.equals("detail.jsp"))) {
			((HttpServletRequest)request).getRequestDispatcher("/public_user/login.jsp").forward(request, response);
		} else {
			chain.doFilter(request, response);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
